/**
 * useDICOMweb Composable
 * 
 * 用于管理 DICOMweb 查询和加载的 Vue 组合式函数
 * 
 * @author yangzhixin
 * @module composables/useDICOMweb
 */

import { ref, type Ref } from 'vue';
import type { CornerstoneFacade } from 'js-3d-model';

/**
 * DICOMweb 配置接口
 */
export interface DICOMwebConfig {
  /** DICOMweb 服务器基础 URL */
  baseUrl: string;
  /** 认证 Token */
  authToken?: string;
  /** QIDO-RS 端点 */
  qidoRoot?: string;
  /** WADO-RS 端点 */
  wadoRoot?: string;
  /** STOW-RS 端点 */
  stowRoot?: string;
}

/**
 * Study 信息接口
 */
export interface StudyInfo {
  /** Study Instance UID */
  studyInstanceUID: string;
  /** Study Date */
  studyDate?: string;
  /** Study Time */
  studyTime?: string;
  /** Study Description */
  studyDescription?: string;
  /** Patient Name */
  patientName?: string;
  /** Patient ID */
  patientID?: string;
  /** Modality */
  modality?: string;
  /** Number of Series */
  numberOfSeries?: number;
  /** Number of Instances */
  numberOfInstances?: number;
}

/**
 * Series 信息接口
 */
export interface SeriesInfo {
  /** Series Instance UID */
  seriesInstanceUID: string;
  /** Study Instance UID */
  studyInstanceUID: string;
  /** Series Number */
  seriesNumber?: number;
  /** Series Description */
  seriesDescription?: string;
  /** Modality */
  modality?: string;
  /** Number of Instances */
  numberOfInstances?: number;
}

/**
 * Instance 信息接口
 */
export interface InstanceInfo {
  /** SOP Instance UID */
  sopInstanceUID: string;
  /** Series Instance UID */
  seriesInstanceUID: string;
  /** Instance Number */
  instanceNumber?: number;
  /** SOP Class UID */
  sopClassUID?: string;
}

/**
 * 查询选项接口
 */
export interface QueryOptions {
  /** 患者姓名 */
  patientName?: string;
  /** 患者ID */
  patientID?: string;
  /** Study Date (YYYYMMDD) */
  studyDate?: string;
  /** Modality */
  modality?: string;
  /** 最大结果数 */
  limit?: number;
  /** 偏移量 */
  offset?: number;
}

/**
 * useDICOMweb 返回类型
 */
export interface UseDICOMwebReturn {
  /** DICOMweb 配置 */
  config: Ref<DICOMwebConfig | null>;
  /** 是否已配置 */
  isConfigured: Ref<boolean>;
  /** 是否正在加载 */
  isLoading: Ref<boolean>;
  /** Studies 列表 */
  studies: Ref<StudyInfo[]>;
  /** Series 列表 */
  series: Ref<SeriesInfo[]>;
  /** Instances 列表 */
  instances: Ref<InstanceInfo[]>;
  /** 错误信息 */
  error: Ref<string | null>;
  /** 配置 DICOMweb */
  configure: (config: DICOMwebConfig) => Promise<void>;
  /** 查询 Studies */
  queryStudies: (options?: QueryOptions) => Promise<StudyInfo[]>;
  /** 查询 Series */
  querySeries: (studyInstanceUID: string) => Promise<SeriesInfo[]>;
  /** 查询 Instances */
  queryInstances: (studyInstanceUID: string, seriesInstanceUID: string) => Promise<InstanceInfo[]>;
  /** 加载 Series 图像IDs */
  loadSeriesImageIds: (studyInstanceUID: string, seriesInstanceUID: string) => Promise<string[]>;
  /** 测试连接 */
  testConnection: () => Promise<boolean>;
}

/**
 * useDICOMweb - DICOMweb 查询和加载
 * 
 * 提供响应式的 DICOMweb 服务集成，包括查询和图像加载
 * 
 * @param facade - CornerstoneFacade 实例
 * @returns DICOMweb 管理方法和状态
 * 
 * @example
 * ```vue
 * <script setup>
 * import { useDICOMweb } from '@/composables/useDICOMweb';
 * import { useCornerstone3D } from '@/composables/useCornerstone3D';
 * 
 * const { facade } = useCornerstone3D();
 * const { 
 *   configure, 
 *   queryStudies, 
 *   querySeries 
 * } = useDICOMweb(facade);
 * 
 * onMounted(async () => {
 *   await configure({
 *     baseUrl: 'http://localhost:8042/dicom-web',
 *     authToken: 'your-token'
 *   });
 *   const studies = await queryStudies({ limit: 10 });
 * });
 * </script>
 * ```
 */
export function useDICOMweb(
  facade: Ref<CornerstoneFacade | null>
): UseDICOMwebReturn {
  // 响应式状态
  const config = ref<DICOMwebConfig | null>(null);
  const isConfigured = ref(false);
  const isLoading = ref(false);
  const studies = ref<StudyInfo[]>([]);
  const series = ref<SeriesInfo[]>([]);
  const instances = ref<InstanceInfo[]>([]);
  const error = ref<string | null>(null);

  /**
   * 配置 DICOMweb 服务
   * 
   * @param newConfig - DICOMweb 配置
   */
  const configure = async (newConfig: DICOMwebConfig): Promise<void> => {
    if (!facade.value) {
      throw new Error('Cornerstone3D 未初始化');
    }

    try {
      isLoading.value = true;
      error.value = null;

      console.log('[useDICOMweb] 配置 DICOMweb:', newConfig.baseUrl);

      await facade.value.configureDICOMweb({
        baseUrl: newConfig.baseUrl,
        authToken: newConfig.authToken,
        qidoRoot: newConfig.qidoRoot,
        wadoRoot: newConfig.wadoRoot,
        stowRoot: newConfig.stowRoot,
      });

      config.value = newConfig;
      isConfigured.value = true;

      console.log('[useDICOMweb] DICOMweb 配置成功');
    } catch (err: any) {
      console.error('[useDICOMweb] 配置失败:', err);
      error.value = err.message || '配置失败';
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 查询 Studies
   * 
   * @param options - 查询选项
   * @returns Studies 列表
   */
  const queryStudies = async (options?: QueryOptions): Promise<StudyInfo[]> => {
    if (!facade.value || !isConfigured.value) {
      throw new Error('DICOMweb 未配置');
    }

    try {
      isLoading.value = true;
      error.value = null;

      console.log('[useDICOMweb] 查询 Studies:', options);
      const result = await facade.value.searchForStudies({
        ...options,
      });

      studies.value = result || [];

      console.log(`[useDICOMweb] 查询到 ${studies.value.length} 个 Studies`);
      return studies.value;
    } catch (err: any) {
      console.error('[useDICOMweb] 查询 Studies 失败:', err);
      error.value = err.message || '查询 Studies 失败';
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 查询 Series
   * 
   * @param studyInstanceUID - Study Instance UID
   * @returns Series 列表
   */
  const querySeries = async (studyInstanceUID: string): Promise<SeriesInfo[]> => {
    if (!facade.value || !isConfigured.value) {
      throw new Error('DICOMweb 未配置');
    }

    try {
      isLoading.value = true;
      error.value = null;

      console.log('[useDICOMweb] 查询 Series:', studyInstanceUID);

      const result = await facade.value.searchForSeries(studyInstanceUID, {});

      series.value = result || [];

      console.log(`[useDICOMweb] 查询到 ${series.value.length} 个 Series`);
      return series.value;
    } catch (err: any) {
      console.error('[useDICOMweb] 查询 Series 失败:', err);
      error.value = err.message || '查询 Series 失败';
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 查询 Instances
   * 
   * 注意：目前 CornerstoneFacade 没有直接的 searchForInstances 方法
   * 通常通过 createImageIdsForSeries 来获取图像 IDs
   * 
   * @param studyInstanceUID - Study Instance UID
   * @param seriesInstanceUID - Series Instance UID
   * @returns Instances 列表
   */
  const queryInstances = async (
    studyInstanceUID: string,
    seriesInstanceUID: string
  ): Promise<InstanceInfo[]> => {
    console.warn('[useDICOMweb] queryInstances 方法暂未实现，请使用 loadSeriesImageIds 代替');
    return [];
    
    // TODO: 如果需要查询 Instances 详情，需要在 CornerstoneFacade 中添加 searchForInstances 方法
    // 目前可以通过 loadSeriesImageIds 直接获取图像 IDs
  };

  /**
   * 加载 Series 的图像 IDs
   * 
   * @param studyInstanceUID - Study Instance UID
   * @param seriesInstanceUID - Series Instance UID
   * @returns 图像 ID 数组
   */
  const loadSeriesImageIds = async (
    studyInstanceUID: string,
    seriesInstanceUID: string
  ): Promise<string[]> => {
    if (!facade.value || !isConfigured.value) {
      throw new Error('DICOMweb 未配置');
    }

    try {
      isLoading.value = true;
      error.value = null;

      console.log('[useDICOMweb] 加载 Series 图像 IDs:', { studyInstanceUID, seriesInstanceUID });

      // 使用 CornerstoneFacade 的方法创建图像 IDs
      const imageIds = await facade.value.createImageIdsForSeries(studyInstanceUID, seriesInstanceUID);

      console.log(`[useDICOMweb] 加载了 ${imageIds.length} 个图像 IDs`);
      return imageIds;
    } catch (err: any) {
      console.error('[useDICOMweb] 加载图像 IDs 失败:', err);
      error.value = err.message || '加载图像 IDs 失败';
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 测试 DICOMweb 连接
   * 
   * @returns 连接是否成功
   */
  const testConnection = async (): Promise<boolean> => {
    if (!facade.value || !isConfigured.value) {
      throw new Error('DICOMweb 未配置');
    }

    try {
      console.log('[useDICOMweb] 测试连接...');

      // 尝试查询 Studies（限制1个）
      await queryStudies({ limit: 1 });

      console.log('[useDICOMweb] 连接测试成功');
      return true;
    } catch (err: any) {
      console.error('[useDICOMweb] 连接测试失败:', err);
      error.value = err.message || '连接测试失败';
      return false;
    }
  };

  return {
    config,
    isConfigured,
    isLoading,
    studies,
    series,
    instances,
    error,
    configure,
    queryStudies,
    querySeries,
    queryInstances,
    loadSeriesImageIds,
    testConnection,
  };
}


